<?php
/**
 * Created by PhpStorm.
 * User: ship
 * Date: 2024/12/26
 * Time: 19:22
 */

namespace ShipSun\LaravelRequestResponseJm;

use Illuminate\Encryption\Encrypter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Class RequestResponseEncrypter
 * @package ShipSun\LaravelRequestResponseJm
 */
class RequestResponseEncrypter
{
    /**
     * @var Encrypter
     */
    protected $encrypter;

    /**
     * RequestEncrypter constructor.
     * @param Encrypter $encrypter
     */
    public function __construct(Encrypter $encrypter)
    {
        $this->encrypter = $encrypter;
    }

    public function encrypt(JsonResponse $response)
    {
        $value = $response->getContent();
        $data = $this->encrypter->encrypt($value, false);

        return new JsonResponse(['encrypt_str' => $data]);
    }

    public function encryptStr($str)
    {
        $data = $this->encrypter->encrypt($str, false);
        return new JsonResponse(['encrypt_str' => $data]);
    }

    public function decrypt(Request $request)
    {
        $all = $request->all();
        $data = $all['encrypt_str'] ?? '';
        unset($all['encrypt_str']);
        if (!is_null($data) && !empty($data)) {
            $originData = $this->encrypter->decrypt($data, false);
            $data = json_decode($originData, true);
        } else {
            $originData = "";
            $data = [];
        }
        return new Request($data, $data, $request->attributes->all(), $request->cookies->all(), $request->files->all(), $request->server->all(), $originData);
    }
}